/*
 * @Author: your name
 * @Date: 2020-07-15 10:31:46
 * @LastEditTime: 2020-07-18 10:54:30
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /waibao/iuyun-device-web/wechat/src/config/request.js
 */

import axios from 'axios';
import host from './host';
import Vue from 'vue';

axios.defaults.headers.common['Accept'] = 'application/json';
axios.defaults.headers.common['Content-Type'] = 'application/json; charset=UTF-8';
axios.defaults.headers.post['Content-Type'] = 'application/json; charset=UTF-8';
axios.defaults.withCredentials = true;

import Cookies from 'js-cookie';

const getUserInfo = function () {
  let userInfo = localStorage.getItem('user');
  if (userInfo) {
    userInfo = JSON.parse(userInfo);
  }
  return userInfo;
};

const getData = function (url, success, error) {
  let userInfo = getUserInfo();

  const config = {
    headers: {
      userId: userInfo ? userInfo.id : '',
    },
  };

  axios
    .get(url, config)
    .then((response) => {
      if (response.data.status == 0 || response.data.success == true) {
        success(response.data.data);
      } else if (response.status === 200) {
        success(response.data);
      } else {
        if (typeof response.data == 'string' && response.data.indexOf('logout') > -1) {
          window.location.href = `${host.wxSsoUrl}/#/?fromUrl=${encodeURIComponent(window.location.href)}`;
        } else if (error) {
          Vue.$vux.loading.hide();
          error(response.data.description);
        } else {
          Vue.$vux.loading.hide();
          Vue.$vux.toast.show({ text: response.data.description || '请求失败', type: 'warn' });
        }
      }
    })
    .catch((e) => {
      if (error) {
        error('网络请求失败');
      }
    });
};

const postData = function (url, data, success, error, headers) {
  const config = {};
  if (headers) {
    config.headers = headers;
  } else {
    config.headers = {};
  }
  let userInfo = getUserInfo();
  if (data) {
    data.userId = userInfo ? userInfo.id : '';
  } else {
    data = { userId: userInfo ? userInfo.id : '' };
  }

  axios
    .post(url, data, config)
    .then((response) => {
      if (response.data.status == 0 || response.data.success == true || response.data.code == 0) {
        success(response.data.data);
      } else {
        if ((typeof response.data == 'string' && response.data.indexOf('logout') > -1) || response.data.status === 99) {
          let domain = location.hostname
            .split('.')
            .slice(1)
            .join('.');
          Cookies.remove('industry', { domain });
          window.location.href = `${host.wxSsoUrl}/#/?fromUrl=${encodeURIComponent(window.location.href)}`;
        } else if (response.status === 200) {
          success(response.data);
        } else if (error) {
          Vue.$vux.loading.hide();
          error(response.data.description);
        } else {
          Vue.$vux.loading.hide();
          Vue.$vux.toast.show({ text: response.data.description || '请求失败', type: 'warn' });
        }
      }
    })
    .catch((e) => {
      if (error) {
        error('网络请求失败');
      }
    });
};

const defaults = ({ method = 'get', url, data = '', params = '', headers = {}, silience = false, error, success }) => {
  let userInfo = getUserInfo();
  if (data) {
    data.userId = userInfo ? userInfo.id : '';
  } else {
    data = { userId: userInfo ? userInfo.id : '' };
  }

  headers.userId = userInfo ? userInfo.id : '';

  axios({
    method,
    url,
    data,
    params,
    headers,
  })
    .then((response) => {
      if (response.data.status == 0 || response.data.success == true || response.data.code == 0) {
        success(response.data.data);
      } else {
        if ((typeof response.data == 'string' && response.data.indexOf('logout') > -1) || response.data.status === 99) {
          let domain = location.hostname
            .split('.')
            .slice(1)
            .join('.');
          Cookies.remove('industry', { domain });
          window.location.href = `${host.wxSsoUrl}/#/?fromUrl=${encodeURIComponent(window.location.href)}`;
        } else if (response.status === 200) {
          success(response.data);
        } else if (error) {
          Vue.$vux.loading.hide();
          error(response.data.description);
        } else {
          Vue.$vux.loading.hide();
          Vue.$vux.toast.show({ text: response.data.description || '请求失败', type: 'warn' });
        }
      }
    })
    .catch((e) => {
      if (error) {
        error('网络请求失败');
      }
    });
};

export default {
  getData,
  postData,
  defaults,
  getUserInfo,
};
